/**
 * @description 工具类
 */

import Vue from 'vue'
import axios from 'axios'
import store from '../store'
import Cookie from 'js-cookie'
import iview from 'iview'
import router from '../router'

const util = {}
/**
 * @description bus实例
 */
util.bus = new Vue()

/**
 *  获取token
 *
 * @returns token
 */
util.getToken = () => {
  return store.state.user.token === ''
    ? (Cookie.get(process.env.VUE_APP_TOKEN) || '')
    : store.state.user.token
}

/**
 * 设置token
 * @param {*} token token
 * @param {*} expires 过期时间 默认1天
 */
util.setToken = (token, expires = 1) => {
  Cookie.set(process.env.VUE_APP_TOKEN, token, { expires })
}

/**
 * @description ajax
 */
util.ajax = axios.create({
  baseURL: window.$config.host,
  timeout: 30000
})

// request拦截器
util.ajax.interceptors.request.use(config => {
  const token = util.getToken()
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
}, err => {
  console.log(err.message)
  Promise.reject(err)
})

util.ajax.interceptors.response.use(res => {
  const data = res.data
  if (data.resultCode === '10000') {
    return data.data
  } else {
    if (data.resultCode === '30000') {
      // 会话过期
      store.commit({ type: 'updateToken', token: '' })
      setTimeout(() => {
        router.push({
          name: 'login'
        })
      }, 100)
    } else {
      iview.Message.warning(data.desc)
    }
    return Promise.reject(new Error(data.desc))
  }
},
err => {
  console.log(`Error:${err.message}`)
  return Promise.reject(err)
})

export default util
